package com.alibaba.datax.common.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ConfigurationUtil {

    public static void persistence(Configuration configuration) throws IOException {
        String resume = System.getProperty("datax.persistence");
        if ("true".equalsIgnoreCase(resume)) {
            String json = configuration.toJSON();
            FileUtils.writeStringToFile(file(configuration), json, StandardCharsets.UTF_8, false);
        }
    }

    public static void remove(Configuration configuration) throws IOException {
        String resume = System.getProperty("datax.persistence");
        if ("true".equalsIgnoreCase(resume)) {
            File file = file(configuration);
            if (file.exists()) {
                FileUtils.forceDelete(file);
            }
        }
    }

    private static File file(Configuration configuration) {
        String workdir = configuration.getString("job.workdir");
        String id = configuration.getString("job._id");
        String name = configuration.getString("job.name");
        return new File(StringUtils.joinWith(File.separator, workdir, id, "configuration", name + ".json"));
    }

}
